package com.gateway.util;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.gateway.entity.LogicServer;

/**
 * 解析XML
 * 
 * @author Simple
 * @date 2013-6-28 02:56:11
 * @Description TODO
 */
public class ParseXML {

  public static void readServerConfig(List<LogicServer> list) {
    try {
      DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
      DocumentBuilder builder=factory.newDocumentBuilder();
      Document doc=builder.parse(new File("config/ServerConfig.xml"));
      Element root=doc.getDocumentElement();
      NodeList servers=root.getChildNodes();
      if(servers != null) {
        for(int i=0; i < servers.getLength(); i++) {
          Node server=servers.item(i);
          if(server.getNodeType() == Node.ELEMENT_NODE) {
            LogicServer serverInfo=new LogicServer();
            for(Node node=server.getFirstChild(); node != null; node=node.getNextSibling()) {
              if(node.getNodeType() == Node.ELEMENT_NODE) {
                if(node.getNodeName().equals("name")) {
                  serverInfo.setName(node.getFirstChild().getNodeValue());
                }
                if(node.getNodeName().equals("ip")) {
                  serverInfo.setIp(node.getFirstChild().getNodeValue());
                }
                if(node.getNodeName().equals("port")) {
                  serverInfo.setPort(Integer.parseInt(node.getFirstChild().getNodeValue()));
                }
              }
            }
            list.add(serverInfo);
          }
        }
      }
    } catch(ParserConfigurationException e) {
      e.printStackTrace();
    } catch(SAXException e) {
      e.printStackTrace();
    } catch(IOException e) {
      e.printStackTrace();
    }
  }
}
